package com.yuecai.config.limit;

import es.moki.ratelimitj.core.limiter.request.RequestLimitRule;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;
import es.moki.ratelimitj.inmemory.request.InMemorySlidingWindowRequestRateLimiter;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;
import java.util.Set;

/**
 * 限流
 */
@Component
public class RateLimitService {

    private Duration duration = Duration.ofMinutes(1);

    private Integer limit = 1;

    public void setDuration(Duration duration) {
        this.duration = duration;
    }

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    Set<RequestLimitRule> rules = Collections.singleton(RequestLimitRule.of(duration, limit));
    RequestRateLimiter requestRateLimiter = new InMemorySlidingWindowRequestRateLimiter(rules);

    public boolean reached(String key){
        return requestRateLimiter.overLimitWhenIncremented(key);
    }
}